package com.zmx.doctor.view.activity;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.bumptech.glide.Glide;
import com.lcw.library.imagepicker.ImagePicker;
import com.wildma.idcardcamera.camera.IDCardCamera;
import com.zmx.doctor.BaseActivity;
import com.zmx.doctor.R;
import com.zmx.doctor.okhttp.OkHttp3ClientManager;
import com.zmx.doctor.pojo.AuthenticationInformation;
import com.zmx.doctor.utils.AllUtil;
import com.zmx.doctor.utils.IDCardValidate;
import com.zmx.doctor.view.util.GlideLoader;
import com.zmx.doctor.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 时间：2020/7/4 16:31
 * 功能：医生认证
 */
public class DoctorCertifiedActivity extends BaseActivity {

    @BindView(R.id.name)
    EditText name;
    @BindView(R.id.edit_id_card)
    EditText editIdCard;
    @BindView(R.id.next_a)
    Button nextA;
    @BindView(R.id.layout_steps_a)
    RelativeLayout layoutStepsA;
    @BindView(R.id.id_card_positive)
    ImageView idCardPositive;
    @BindView(R.id.id_card_reverse)
    ImageView idCardReverse;
    @BindView(R.id.next_b)
    Button nextB;
    @BindView(R.id.layout_steps_b)
    LinearLayout layoutStepsB;
    @BindView(R.id.licensed_a)
    ImageView licensedA;
    @BindView(R.id.licensed_b)
    ImageView licensedB;
    @BindView(R.id.next_c)
    Button nextC;
    @BindView(R.id.layout_steps_c)
    LinearLayout layoutStepsC;
    @BindView(R.id.message_layout)
    LinearLayout messageLayout;
    @BindView(R.id.message_name)
    TextView messageName;
    @BindView(R.id.message_number)
    TextView messageNumber;
    @BindView(R.id.shenfen_a)
    ImageView shenfenA;
    @BindView(R.id.shenfen_b)
    ImageView shenfenB;
    @BindView(R.id.zhiye_a)
    ImageView zhiyeA;
    @BindView(R.id.zhiye_b)
    ImageView zhiyeB;
    @BindView(R.id.message_hosp)
    TextView messageHosp;
    @BindView(R.id.message_class)
    TextView messageClass;
    @BindView(R.id.message_title)
    TextView messageTitle;
    @BindView(R.id.message_state)
    TextView messageState;
    private Toolbar toolbar;

    private AuthenticationInformation ai;

    private int REQUEST_SELECT_IMAGES_CODE_A = 1;
    private String imagePath_a = "";//本地的图片
    private String imagePath_b = "";//本地的图片

    private int state_a = 0;

    private String idcard_a = "";
    private String idcard_v = "";

    private Integer steps = 1;

    @Override
    protected int getLayoutId() {

        return R.layout.activity_doctor_certified;

    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);
        ai = new AuthenticationInformation();

        toolbar = findViewById(R.id.tool_bar);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (steps == 1) {
                    finish();
                    return;
                } else if (steps == 2){

                    finish();

                }else if (steps == 3){

                }

            }
        });


        authInfo();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        if (resultCode == IDCardCamera.RESULT_CODE) {
            //获取图片路径，显示图片
            final String path = IDCardCamera.getImagePath(data);

            if (!TextUtils.isEmpty(path)) {
                if (requestCode == IDCardCamera.TYPE_IDCARD_FRONT) {

                    //身份证正面
                    idcard_a = path;
                    upload(path, state_a);

                } else if (requestCode == IDCardCamera.TYPE_IDCARD_BACK) {
                    //身份证反面
                    idcard_v = path;
                    upload(path, state_a);

                }
            }
        }

        if (requestCode == REQUEST_SELECT_IMAGES_CODE_A && resultCode == RESULT_OK) {

            List<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);

            for (String s : imagePaths) {


                if (state_a == 3) {
                    imagePath_a = s;
                } else {
                    imagePath_b = s;

                }

                upload(imagePath_a, state_a);

            }

        }


    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    ImagePicker.getInstance()
                            .setTitle("标题")//设置标题
                            .showCamera(true)//设置是否显示拍照按钮
                            .showImage(true)//设置是否展示图片
                            .showVideo(false)//设置是否展示视频
                            .setSingleType(true)//设置图片视频不能同时选择
                            .setMaxCount(1)//设置最大选择图片数目(默认为1，单选)
                            .setImageLoader(new GlideLoader())//设置自定义图片加载器
                            .start(mActivity, REQUEST_SELECT_IMAGES_CODE_A);//REQEST_SELECT_IMAGES_CODE为Intent调用的requestCode

                    break;

                case 2:

                    switch (state_a) {

                        case 1:

                            idCardPositive.setImageBitmap(BitmapFactory.decodeFile(idcard_a));

                            break;
                        case 2:

                            idCardReverse.setImageBitmap(BitmapFactory.decodeFile(idcard_v));
                            break;
                        case 3:

                            licensedA.setImageBitmap(BitmapFactory.decodeFile(imagePath_a));
                            break;
                        case 4:

                            licensedB.setImageBitmap(BitmapFactory.decodeFile(imagePath_b));
                            break;
                    }

                    break;

                case 3:

                    Log.e("数据", "数据" + msg.obj.toString());

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        if (object.getInt("code") == 1) {

                            JSONObject data = object.getJSONObject("data");

                            messageLayout.setVisibility(View.VISIBLE);

                            messageName.setText("姓    名："+data.getString("name"));
                            messageNumber.setText("身份证："+data.getString("idcard"));
                            Glide.with(mActivity).load(data.getString("card")).into(shenfenA);
                            Glide.with(mActivity).load(data.getString("cardside")).into(shenfenB);
                            Glide.with(mActivity).load(data.getString("prove")).into(zhiyeA);
                            Glide.with(mActivity).load(data.getString("openprove")).into(zhiyeB);
                            messageHosp.setText("医    院："+data.getString("hosp_name"));
                            messageClass.setText("科    室："+data.getString("class_name"));
                            messageTitle.setText("称    号："+data.getString("title_name"));

                            if (data.getInt("auth") == 0){

                                messageState.setText("状态：审核中");

                            }else if(data.getInt("auth") == 1){

                                messageState.setText("状态：认证通过");

                            }else if(data.getInt("auth") == 2){

                                messageState.setText("状态：认证未通过\n 原因："+data.getString("reason"));

                            }

                        } else {

                            layoutStepsA.setVisibility(View.VISIBLE);

                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

            }

        }
    };


    @OnClick({R.id.next_a, R.id.id_card_positive, R.id.id_card_reverse, R.id.next_b, R.id.licensed_a, R.id.licensed_b, R.id.next_c})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.next_a:

                //判断有没有输入
                if (name.getText().toString().equals("")) {

                    Toast("请输入名字");
                    return;
                }
                if (editIdCard.getText().toString().equals("")) {

                    Toast("请输入身份证号");
                    return;
                }

                if (!IDCardValidate.validate_effective(editIdCard.getText().toString())) {
                    Toast("请输入正确的身份证号");
                    return;
                }

                ai.setName(name.getText().toString());
                ai.setIdcard(editIdCard.getText().toString());

                layoutStepsA.setVisibility(View.GONE);
                layoutStepsB.setVisibility(View.VISIBLE);

                steps = 2;

                break;
            case R.id.id_card_positive:

                state_a = 1;

                IDCardCamera.create(this).openCamera(IDCardCamera.TYPE_IDCARD_FRONT);
                break;
            case R.id.id_card_reverse:
                state_a = 2;
                IDCardCamera.create(this).openCamera(IDCardCamera.TYPE_IDCARD_BACK);

                break;
            case R.id.next_b:

//                FileUtils.clearCache(this); 删除缓存图片

                if (ai.getCard() == null || ai.getCard().equals("")) {

                    Toast("请上传身份证正面图");
                    return;

                }
                if (ai.getCardside() == null || ai.getCardside().equals("")) {

                    Toast("请上传身份证反面图");
                    return;

                }

                layoutStepsB.setVisibility(View.GONE);
                layoutStepsC.setVisibility(View.VISIBLE);
                steps = 3;
                break;

            case R.id.licensed_a:

                state_a = 3;
                handler.sendEmptyMessage(1);

                break;
            case R.id.licensed_b:

                state_a = 4;
                handler.sendEmptyMessage(1);

                break;
            case R.id.next_c:

                if (ai.getProce() == null || ai.getProce().equals("")) {

                    Toast("请上传执业证第一页");
                    return;

                }
                if (ai.getOpenprove() == null || ai.getOpenprove().equals("")) {

                    Toast("请上传执业证第二页");
                    return;

                }

                steps = 4;
                Bundle bundle = new Bundle();
                bundle.putSerializable("ai", ai);
                startActivity(HospitalListActivity.class, bundle);
                finish();

                break;
        }
    }


    private void upload(String url, int state) {// selImageList 包含图片路径的list


        OkHttpClient okHttpClient = new OkHttpClient();

        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM); //表单上传文件


        File file = new File(url); //根据路径创建file对象
        builder.addFormDataPart("image[]", //
                file.getName(),
                RequestBody.create(MediaType.parse("image/jpeg"), file)
        );

        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .url("http://zmx.123xk.cn/admin/api.doctor/AddImg")
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure: ", e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                try {

                    JSONObject object = new JSONObject(response.body().string());

                    Log.e("数据","数据"+object.toString());

                    if (object.getString("code").equals("1")) {

                        JSONObject data = object.getJSONObject("data");
                        JSONArray array = data.getJSONArray("path");
                        for (int i = 0; i < array.length(); i++) {

                            if (state == 1) {

                                ai.setCard(array.get(i).toString());

                            } else if (state == 2) {

                                ai.setCardside(array.get(i).toString());

                            } else if (state == 3) {

                                ai.setProce(array.get(i).toString());

                            } else if (state == 4) {

                                ai.setOpenprove(array.get(i).toString());

                            }

                        }

                        handler.sendEmptyMessage(2);

                    } else {
                        Toast(object.getString("msg"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

    }


    public void authInfo() {

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(null)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "authInfo");
        params.put("data[]", "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app", params, handler, 3, 404);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}


